#region DocumentHeader
// =============================================    
// Author       : PRUDHVI  
// Create date  : 10.11.2013
// Purpose      : Controller for Execute actions for layout view
// ============================================= 
#endregion

#region Name Spaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using log4net;
using System.Web.UI;
using Lens.com.Models;
using LenseAPIService.DataAccessLayer;
using System.Net.Mail;
using System.Configuration;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
//using System.Web.Mail;

using LenseAPIService.DataAccessLayer;
using log4net;
#endregion
namespace Lens.com.Controllers
{
    public class LayoutController : Controller
    {
        #region Private Member Varibles
        DataAccess objDataAccess = new DataAccess();
        private static readonly ILog Log = LogManager.GetLogger(typeof(RegistrationController));
        #endregion

        #region Public Action Methods
        /// <summary>
        ///  author          :       Anusha
        ///  Created         :       10.11.2013
        ///  Purpose         :       This Action method Will perform auto fill for crops in Search crops 
        /// </summary>
        /// <returns>
        /// It will take user to login page.
        /// </returns>
        [HttpGet]
        public JsonResult GetProducts(string query = "")
        {
            // Adds Try Catch Block along with Log file.
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {
                LayoutModel layout = new LayoutModel();

                IEnumerable<DataRow> datarows = objDataAccess.GetAttributeMaster(GlobalConstants.crop);//"Crop");
                var result = datarows.Select(p => new LayoutModel
                {
                    AttrubuteId = p.Field<int>(GlobalConstants.Cropid),//"CropId"),
                    AttributeName = p.Field<string>(GlobalConstants.CropName)//"CropName")
                });

                var Searchresult = string.IsNullOrEmpty(query) ? result :
                    result.Where(p => p.AttributeName.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0).ToList();

                return Json(Searchresult, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

        //commented by sumanth, this action method may be not using
        //[HttpPost]
        //public ActionResult buttonSubmit(FormCollection coll)
        //{
        //    return View();
        //}



        /// </summary>
        ///  author          :       Sumanth.J
        ///  Created         :       23.11.2013
        ///  Purpose         :       This Action method Will get all predective analysis for crop,irrigation and soil 
        /// </summary>
        /// <returns>
        /// It will return Crop,Irrigation,Soil names and count of the lense respectively
        /// <returns>
        [ChildActionOnly]
        public ActionResult predictiveAnalysis()
        {
            // Adds Try Catch Block along with Log file.
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {

                    LayoutModel layout = new LayoutModel();
                    List<LayoutModel> objlayout = new List<LayoutModel>();
                    DataSet dtReportImages = objDataAccess.GetPredictiveAnalysisSearch();
                    int dtCount = dtReportImages.Tables.Count;
                    for (int i = 0; i < dtCount; i++)
                    {
                        if (dtReportImages.Tables[i] != null)
                        {
                            if (dtReportImages.Tables[i].Rows.Count > 0)
                            {
                                layout.lensecount=dtReportImages.Tables[i].Rows[0][0].ToString();
                                layout.cropName=dtReportImages.Tables[i].Rows[0][1].ToString();
                                layout.OnlyCropName = dtReportImages.Tables[i].Rows[0][2].ToString();

                                objlayout.Add(layout);
                            }
                        }
                    }
                    return PartialView(objlayout);
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

        /// <summary>
        ///  author          :       Anusha
        ///  Created         :       10.11.2013
        ///  Purpose         :       This Action method Will perform logout functionality 
        /// </summary>
        /// <returns>
        /// It will take user to login page.
        /// </returns>
        public ActionResult LogOut()
        {
            // Adds Try Catch Block along with Log file.
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {               
                Session.Clear();
                Session.Abandon();                                             
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
            return  RedirectToAction(GlobalConstants.Index, GlobalConstants.PhotoGallery);
        }

        /// <summary>
        ///  author          :       Anusha
        ///  Created         :       13.12.2013
        ///  Purpose         :       This Action method Will validate user Login
        /// </summary>
        /// <returns>
        /// It will take user to login page.
        /// </returns>
        public ActionResult Login(string Command,FormCollection coll)
        {
            if (Command == GlobalConstants.Login)
            {
                string username = coll[GlobalConstants.master_txtUserName];
                string password = coll[GlobalConstants.master_txtPassword];
                password = EncriptManager.Encrypt(password);
                int isValiduser = objDataAccess.ValidateUser(username, password);
                if (isValiduser > 0)
                {
                    Session[GlobalConstants.strUserID] = isValiduser;
                    string MobileNo = objDataAccess.GetUserInfo(Convert.ToString(Session[GlobalConstants.strUserID]));
                    Session[GlobalConstants.strMobileNo] = MobileNo;
                    Session[GlobalConstants.strDisableLogin] = "1";
                }
                else
                {
                    ViewBag.Success = GlobalConstants.strInvalidUser;
                }
            }
            return RedirectToAction(GlobalConstants.strIndex, GlobalConstants.strPhotoGallery);

        }

        //[HttpPost]
        //[MultiButton(Name = "TxtTellAFriend", Argument = "SignIn")]
        public ActionResult Tellafriend(string TxtTellAFriend)
        {
            string friendEmailorSms = TxtTellAFriend;
            SendEmailorSms(friendEmailorSms);
            return View();
        }

        //[HttpPost]

        public void SendEmailorSms(string emailorsms)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {
                if (IsEmail(emailorsms))
                {
                    StringBuilder strBody = new StringBuilder();
                    if (emailorsms.Trim().Length > 0)
                    {
                        string[] usr = emailorsms.Split('@');
                        string username = usr[0].ToString();
                        //create the mail message
                        MailMessage mail = new MailMessage();
                        SmtpClient smtp = new SmtpClient();
                        string appURL = ConfigurationManager.AppSettings["appURL"].ToString();
                        mail.From = new MailAddress(ConfigurationManager.AppSettings["EmailFromAddr"].ToString());
                        mail.To.Add(emailorsms);
                        mail.IsBodyHtml = true;
                        mail.Subject = "Message from Croplense";

                        strBody.Append("<html><head></head><body><table width=100% border=0 cellspacing=0 cellpadding=0>");
                        strBody.Append(" <tr><td align=left valign=middle style=font-weight:normal; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; color:000000;line-height:120%>");
                        strBody.Append("  <br/> <b> " + GlobalConstants.Dear + " </b> " + username.ToString() + "<br/><br/> ");
                        strBody.Append("<p style=\"margin:0; font-size: 15px;  color: #014F9A; font-family: Arial; line-height: 18px;\">");
                        strBody.Append("Hi, I have found CropLense interesting with it's knowledge and content on agri, Please visit WWW.croplense.com for details.  <br /></p><br/>");
                        strBody.Append("</td>");
                        strBody.Append("</tr>");
                        strBody.Append("</table>");
                        strBody.Append("</body></html>");

                        mail.Body = strBody.ToString();

                        smtp.Host = ConfigurationManager.AppSettings["EmailHostAddr"].ToString();
                        smtp.Port = int.Parse(ConfigurationManager.AppSettings["EmailHostPort"].ToString());
                        smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["EmailHostUID"].ToString(), ConfigurationManager.AppSettings["EmailHostPwd"].ToString());
                        smtp.EnableSsl = true;
                        smtp.Send(mail);
                        //return View(true);
                    }

                }
                else
                {
                    SendSMSUnicell(emailorsms);
                }
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

        public bool IsEmail(string emailorsms)
        {
            bool isemail = false;
            if (emailorsms.Contains('@'))
            {
                isemail = true;
            }

            return isemail;
        }

        private void SendSMSUnicell(string sms)
        {
            // Adds Try Catch Block along with Log file.
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {
                System.Net.HttpWebRequest fr;
                string strMessage = GlobalConstants.Dear + sms + "," + " " + "Hi,I have found CropLense interesting with it's knowledge and content on agri,Please visit WWW.croplense.com for details.";
                Uri targetUri = new Uri("http://www.pointsms.in/API/sms.php?username=iConcept&password=change&from=CLense&to=" + sms + "&msg=" + strMessage + "&type=1&dnd_check=0");

                fr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(targetUri);

                if ((fr.GetResponse().ContentLength > 0))
                {

                    System.IO.StreamReader str = new System.IO.StreamReader(fr.GetResponse().GetResponseStream());

                    //Response.Write(str.ReadToEnd());

                    string strReply = str.ReadToEnd();

                    decimal decrep = Convert.ToDecimal(strReply);

                    if (str != null)

                        str.Close();
                }

            }

            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }
        public ActionResult Terms()
        {
            return View("Terms");
        }
    }

        #endregion

}
